package multithread.print_by_turn;

import java.util.concurrent.Semaphore;

class FooBar {
    Semaphore barSemaphore = new Semaphore(0);
    Semaphore fooSemaphore = new Semaphore(1);
    private int n;

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo){
        try {
            for (int i = 0; i < n; i++) {
                fooSemaphore.acquire();
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            barSemaphore.release();
        }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public void bar(Runnable printBar) {
        try {
            for (int i = 0; i < n; i++) {
                barSemaphore.acquire();
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                fooSemaphore.release();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class PrintFoo implements Runnable{
        @Override
        public void run() {
            System.out.print("foo");
        }
    }

    static class PrintBar implements Runnable{
        @Override
        public void run() {
            System.out.print("bar");
        }
    }
}